package com.origin.ebuy.bargd.dao.user.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.origin.ebuy.bargd.dao.user.IUserDao;
import com.origin.ebuy.dao.comm.BaseDao;
import com.origin.ebuy.dao.comm.ResultHandler;

public class UserDaoImpl extends BaseDao implements IUserDao {

	/**
	 * 根据用户名称查询用户<br>
	 * 查到到数据返回1,<br>
	 * 没有查询到返回-1<br>
	 */
	@Override
	public JSONObject queryUserByName(String name) throws SQLException {
		final String[] parames = {name};
		final String[] cols = {"id","uname","passwd","rule","state"};
		final ResultHandler handler = new ResultHandler() {
			@Override
			public Object handler(ResultSet res) throws SQLException {
				JSONObject object = new JSONObject();
				if(res.next()){
					object.put("id", res.getString("id"));
					object.put("uname", res.getString("uname"));
					object.put("passswd", res.getString("passwd"));
					object.put("rule", res.getString("rule"));
					object.put("state", res.getString("state"));
				}
				return object;
			}
		};
		return (JSONObject)query("users",cols, "uname=?", parames,handler);
	}

	@Override
	public int insertUser(String name, String passwd) throws SQLException {
		String cols[] = {"uname","passwd"};
		Object[] parames = {name,passwd};
		return insert("users", cols, parames);
	}

	/**
	 * 查询所有的用户
	 */
	@Override
	public JSONArray queryAllUser() throws SQLException {
		final String[] cols = {"id","uname","rule","state"};
		Object[] obj = null;
		final ResultHandler handler = new ResultHandler() {
			@Override
			public Object handler(ResultSet res) throws SQLException {
				JSONArray array = new JSONArray();
				while(res.next()){
					JSONObject object = new JSONObject();
					object.put("id", res.getString("id"));
					object.put("uname", res.getString("uname"));
					object.put("rule", res.getString("rule"));
					object.put("state", res.getString("state"));
					array.add(object);
				}
				return array;
			}
		};
		return (JSONArray)query("users", cols, null, obj, handler);
	}

	/**
	 * 更新用户信息
	 */
	@Override
	public int updateUser(String whre, String[] cols, Object[] params)
			throws SQLException {
		return update("users", cols,whre, params);
	}

}
